package jjn.carl.array;

import java.util.Arrays;

/**
 * @author Jiang Jining
 * @since 2023-06-29 23:01
 */
public class LeetCode59 {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int left = 0, right = n - 1, top = 0, bottom = n - 1, current = 1;
        while (true) {
            for (int i = left; i <= right; i++, current++) {
                result[top][i] = current;
            }
            top++;
            if (top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++, current++) {
                result[i][right] = current;
            }
            right--;
            if (right < left) {
                break;
            }
            for (int i = right; i >= left; i--, current++) {
                result[bottom][i] = current;
            }
            bottom--;
            if (bottom < top) {
                break;
            }
            for (int i = bottom; i >= top; i--, current++) {
                result[i][left] = current;
            }
            left++;
            if (left > right) {
                break;
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        int[][] generatedMatrix = new LeetCode59().generateMatrix(3);
        for (int[] matrix : generatedMatrix) {
            System.out.println(Arrays.toString(matrix));
        }
    }
    
}
